package com.amkor.web.common.advice;

import java.util.List;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class JsonAdvice implements MethodInterceptor {
	private Gson gson;
	
	public void setGson(Gson gson){
		this.gson = gson;
	}

	public Object invoke(MethodInvocation invocation) throws Throwable {
		try{
			
			Object ret = invocation.proceed();			
			if(ret == null)	
				throw new RuntimeException("Return for JsonAdvice is null !!");
				
			if(ret instanceof List<?>){
				List<?> list = (List<?>)ret;
				JsonObject jo = new JsonObject();
				jo.add("root", gson.toJsonTree(list));
				jo.addProperty("success", true);
				return jo.toString();
			}else{
				JsonObject jo = new JsonObject();
				jo.addProperty("success", true);
				return gson.toJson(ret);
			}
						
		}catch(RuntimeException e){
			throw e;
		}										
	}

}
